package com.rongji.egov.fileupload.rjfile;

import com.rongji.egov.fileupload.client.FileClientChannelInitializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NettyFileClient {
    private final static Logger logger = LoggerFactory.getLogger(NettyFileClient.class);
    Bootstrap bootstrap = new Bootstrap();
    private final EventLoopGroup workerGroup = new NioEventLoopGroup(16);

    private final String host;
    private final int port;

    public NettyFileClient(String host, int port){
        this.host = host;
        this.port = port;
        bootstrap.group(workerGroup);
        bootstrap.channel(NioSocketChannel.class);
        //b.option(ChannelOption.AUTO_READ, true);
        bootstrap.handler(new FileClientChannelInitializer());
    }

    public ChannelFuture connect() {
        ChannelFuture channelFuture = null;
        try{
            channelFuture = bootstrap.connect(host, port)
                    .syncUninterruptibly();

            if (null != channelFuture && channelFuture.isSuccess()) {
                logger.info("{}:{}文件服务端连接成功！", host, port);
            } else {
                String msg = String.format("无法连接文件服务端%s:%s", host, port);
                logger.error(msg);
                throw new RuntimeException(msg);
            }
        } catch (Exception e) {
            String msg = String.format("无法连接文件服务端%s:%s", host, port);
            logger.error(msg, e);
            throw new RuntimeException(msg + "##" +  e.getMessage(), e);
        }
        return channelFuture;
    }

    public void destroy() {
        workerGroup.shutdownGracefully();
    }

}
